package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
@Transactional
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService paramService;
    /**
     * 根据分类id查询规格组及组内参数
     * @param categoryId
     * @return
     */
    @Override
    public List<SpecGroupDTO> querySpecGroupAndSpecParamByCategoryId(Long categoryId) {

        //根据分类id直接在规格参数中查询
        List<SpecParam> specParamList = paramService.query().eq("category_id", categoryId).list();
        List<SpecParamDTO> specParamDTOList = SpecParamDTO.convertEntityList(specParamList);
        //根据group_id进行分类，将相同id的放在一个集合中 用group_id作为可以进行标记
        Map<Long, List<SpecParamDTO>> map = specParamDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //根据分类id查询规格组
        List<SpecGroup> specGroupList = query().eq("category_id", categoryId).list();
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        }
       /* List<SpecGroup> specGroupList = query().eq("category_id", categoryId).list();
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            Long groupId = specGroupDTO.getId();
            List<SpecParam> specParamList = paramService.query().eq("group_id", groupId).list();
            List<SpecParamDTO> specParamDTOList = SpecParamDTO.convertEntityList(specParamList);
            specGroupDTO.setParams(specParamDTOList);
        }*/


        return specGroupDTOList;
    }
}